package abaco.gui;

import java.awt.Component;
import java.awt.Font;
import java.util.HashMap;

import javax.swing.JComponent;
import javax.swing.JPanel;

import abaco.Symbol;

public class Panel extends JPanel{
	public static final int FONT_SIZE_STANDARD = 30;
	public static final int FONT_SIZE_MINIMAL = 18;
	public static final int FONT_SIZE_DECREASE = 3;

	private Symbol symbol = null;
	private boolean makeFontSmaller = false;

	public Panel(Symbol symbol) {
		this.symbol = symbol;
	}

	public Symbol getSymbol() {
		return symbol;
	}

	public Panel setMakeFontSmaller(boolean flag) {
		makeFontSmaller = flag;
		return this;
	}

	public boolean getMakeFontSmaller() {
		return makeFontSmaller;
	}

	public Panel refreshFontSize() {
		// trigger children
		HashMap<String, Symbol> children = symbol.getSymbolChildren();
		if (null != children) {
			for (Symbol child : children.values()) {
				(new Drawer(child)).getPanel().refreshFontSize();
			}
		}

		// calculate how small this must be
		int size = howSmallIsfontSize();
		size = FONT_SIZE_STANDARD - (size * FONT_SIZE_DECREASE);
		if (size < FONT_SIZE_MINIMAL) {
			size = FONT_SIZE_MINIMAL;
		}
		setFontSize(size);

		return this;
	}

	protected int howSmallIsfontSize() {
		int size = 0;
		Symbol s = symbol;
		do {
			if ((new Drawer(s)).getPanel().makeFontSmaller) {
				size++;
			}
		} while (null != (s = s.getSymbolParent()));
		return size;
	}

	protected void setFontSize(int size) {
		Font font = new Font("Monospaced", Font.PLAIN, size);
		for (Component child : getComponents()) {
			if (child instanceof JComponent) {
				((JComponent) child).setFont(font);
			}
		}
	}
}
